package com.wv.api.server.common;


import cn.dev33.satoken.util.SaResult;
import cn.hutool.db.Page;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.wv.common.exception.WVException;
import com.wv.common.result.HttpCodeEnum;
import com.wv.model.common.constants.ExcelConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
public class BaseController {

    /**
     * 返回成功
     * @return
     */
    public SaResult success() {
        return SaResult.ok();
    }

    /**
     * 返回成功
     * @return
     */
    public SaResult success(String msg) {
        return SaResult.ok(msg);
    }

    /**
     * 返回成功
     * @param data 数据
     * @return
     */
    public SaResult success(Object data){
        return SaResult.ok().setData(data);
    }

    public SaResult success(HttpCodeEnum httpCodeEnum){
        return SaResult.ok().setCode(httpCodeEnum.getCode()).setMsg(httpCodeEnum.getMsg());
    }


    /**
     * 返回失败
     * @param httpCodeEnum 失败枚举
     * @return
     */
    public SaResult error(HttpCodeEnum httpCodeEnum){
        return SaResult.error(httpCodeEnum.getMsg()).setCode(httpCodeEnum.getCode());
    }

    /**
     * 返回失败
     * @param msg 失败消息
     * @return
     */
    public SaResult error(String msg){
        return SaResult.error(msg);
    }

    /**
     * 导出表格
     * @param response 响应体
     * @param list 数据
     * @param objectClass 具体类
     * @param filename 文件名
     * @return
     */
    public SaResult outExcel(HttpServletResponse response,List list,Class objectClass,String filename) {
        try {
            this.setExcelResponseProp(response,filename);
            EasyExcel.write(response.getOutputStream())
                    .head(objectClass)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet(filename)
                    .doWrite(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return SaResult.ok();
    }
    /**
     * 导入表格
     * @param file 文件
     * @param clazz 具体类
     * @return
     */
    public List inputExcel(@RequestPart("file") MultipartFile file,Class clazz)     {
        try {
            return EasyExcel.read(file.getInputStream())
                    .head(clazz)
                    .sheet()
                    .doReadSync();
        } catch (IOException e) {
            throw new WVException(HttpCodeEnum.ERROR);
        }
    }

//    public void exportSurfList2(HttpServletResponse response) throws IOException {
//        log.info("*********地面统计查询列表导出开始！**************");
//        //文件名
//        String fileName =String.valueOf(System.currentTimeMillis());
//
//        OutputStream outputStream =null;
//        try {
//            //记录总数:实际中需要根据查询条件进行统计即可:一共多少条
//            int totalCount = mapper.seleCount();
//            //每一个Sheet存放100w条数据
//            Integer sheetDataRows = ExcelConstants.PER_SHEET_ROW_COUNT;
//            //每次写入的数据量20w,每页查询20W
//            Integer writeDataRows = ExcelConstants.PER_WRITE_ROW_COUNT;
//            //计算需要的Sheet数量
//            Integer sheetNum = totalCount % sheetDataRows == 0 ? (totalCount / sheetDataRows) : (totalCount / sheetDataRows + 1);
//            //计算一般情况下每一个Sheet需要写入的次数(一般情况不包含最后一个sheet,因为最后一个sheet不确定会写入多少条数据)
//            Integer oneSheetWriteCount = sheetDataRows / writeDataRows;
//            //计算最后一个sheet需要写入的次数
//            Integer lastSheetWriteCount = totalCount % sheetDataRows == 0 ? oneSheetWriteCount : (totalCount % sheetDataRows % writeDataRows == 0 ? (totalCount / sheetDataRows / writeDataRows) : ((totalCount % sheetDataRows)+ / writeDataRows + 1));
//            outputStream = response.getOutputStream();
//            //必须放到循环外，否则会刷新流
//            ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
//            //开始分批查询分次写入
//            for (int i = 0; i < sheetNum; i++) {
//                //创建Sheet
//                WriteSheet sheet = new WriteSheet();
//                sheet.setSheetName("Sheet"+i);
//                sheet.setSheetNo(i);
//                //循环写入次数: j的自增条件是当不是最后一个Sheet的时候写入次数为正常的每个Sheet写入的次数,如果是最后一个就需要使用计算的次数lastSheetWriteCount
//                for (int j = 0; j < (i != sheetNum - 1 ? oneSheetWriteCount : lastSheetWriteCount); j++) {
//                    //分页查询一次20w
//                    Page page1 = new Page(j + 1 + oneSheetWriteCount * i, writeDataRows);
//                    //查询分页列表---按照自己的业务查列表，分页这个一定要使用这个：page1.getPageNum(),page1.getPageSize()！！！
//                    List<Map<String, Object>> list = mapper.selectList(page1.getPageNumber(),page1.getPageSize());
//                    //写入到excel:
//                    /**************z只需要选择一种方式即可*****************/
//                    //这里可以通过设置includeColumnFiledNames、excludeColumnFiledNames导出什么字段，可以动态配置，前端传过来那些列，就导出那些列
////                    //方式1、只导出v01301这一列
////                    Set<String> includeColumnFiledNames = new HashSet<String>();
////                    includeColumnFiledNames.add("v01301");
////                    WriteSheet writeSheet = EasyExcel.writerSheet(i, "Sheet" + (i + 1)).head(AltitudeMonExportExcelVO.class).includeColumnFiledNames(includeColumnFiledNames)
////                            .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
////                    //方式2、排除v01301这一列，其他的全部导出
////                    Set<String> excludeColumnFiledNames = new HashSet<String>();
////                    excludeColumnFiledNames.add("v01301");
////                    WriteSheet writeSheet = EasyExcel.writerSheet(i, "Sheet" + (i + 1)).head(AltitudeMonExportExcelVO.class).excludeColumnFiledNames(includeColumnFiledNames)
////                            .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
////                    excelWriter.write(list, writeSheet);
//                    //方式3、不做设置，全部导出
//                    WriteSheet writeSheet = EasyExcel.writerSheet(i, "Sheet" + (i + 1)).head(AltitudeMonExportExcelVO.class)
//                            .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
//                    excelWriter.write(list, writeSheet);
//                }
//            }
//            // 下载EXCEL，返回给前段stream流
//            response.setContentType("application/octet-stream");
//            response.setCharacterEncoding("utf-8");
//            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//            excelWriter.finish();
//            outputStream.flush();
//            outputStream.close();
//            log.info("*********地面统计查询列表导出结束！**************");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            if (outputStream != null) {
//                outputStream.close();
//            }
//        }
//
//    }


    /**
     * 设置响应结果
     * @param response    响应结果对象
     * @param rawFileName 文件名
     * @throws UnsupportedEncodingException 不支持编码异常
     */
    private void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

}
